package sjc;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * 分布式计数器
 */
public class AtomicIntegerTest {
    /** session超时时间 */
    static final int SESSION_OUTTIME = 5000; //ms

    public static void main(String[] args) throws Exception {
        //1 重试策略：初次间隔时间为1s 重试 10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //2 通过工厂创建连接
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.72.133:2181")
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();
        //3 开启连接
        client.start();
        //cf.delete().forPath("/super");


        //4 使用DistributedAtomicInteger
        DistributedAtomicInteger atomicIntger = new DistributedAtomicInteger(client, "/distribute/atomic", retryPolicy);

        AtomicValue<Integer> value = atomicIntger.add(3);
        System.out.println("操作状态："+value.succeeded());
        System.out.println("原始值: "+value.preValue());	//原始值
        System.out.println("最新值: "+value.postValue());	//最新值

    }
}
